package com.jrx.anytxn.param.job.paph.config;


import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.Md5utils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.config.PaphConfig;
import com.jrx.anytxn.param.config.PaphSftpConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author 张靖烽
 * @name DownloadRepayFileConfiguration
 * @description 下载正常还款文件批量
 * @create 2021-03-12 17:53
 **/
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class DownloadRepayFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DownloadRepayFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private PaphConfig paphConfig;
    @Autowired
    private PaphSftpConfig paphSftpConfig;

    @Bean
    public Job downloadRepayFileJob() {
        return jobBuilderFactory.get("downloadRepayFileJob")
                .start(downloadRepayFileStep())
                .build();
    }

    @Bean
    public Step downloadRepayFileStep() {
        return stepBuilderFactory.get("downloadRepayFileStep")
                .tasklet(downloadRepayFileTasklet())
                .build();
    }


    @Bean
    @StepScope
    public Tasklet downloadRepayFileTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String date = DateFormatUtils.format(org.getNextProcessingDate(), DateUtils.DATE_PATTERN_ANOTHER);
            // 文件路径
            String path = paphSftpConfig.getDownloadPath();
            // 消费贷 txt md5
            String xfTxtFile = Constant.LS_BANK + Constant.PRODECUT_TYPE_XF + date + Constant.SERVICE_TYPE + ".txt";
            String xfMd5File = Constant.LS_BANK + Constant.PRODECUT_TYPE_XF + date + Constant.SERVICE_TYPE + ".md5";
            // 经营贷 txt md5
            String jyTxtFile = Constant.LS_BANK + Constant.PRODECUT_TYPE_JY + date + Constant.SERVICE_TYPE + ".txt";
            String jyMd5File = Constant.LS_BANK + Constant.PRODECUT_TYPE_JY + date + Constant.SERVICE_TYPE + ".md5";
            // 本地路径
            String xfLocalPath = paphConfig.getRepayResultFilePath() + org.getTenantId() + File.separator + date + File.separator + Constant.PRODECUT_TYPE_XF + File.separator;
            String jyLocalPath = paphConfig.getRepayResultFilePath() + org.getTenantId() + File.separator + date + File.separator + Constant.PRODECUT_TYPE_JY + File.separator;
            //1 获取连接
            SftpUtils.sftpConnect(paphSftpConfig.getUsername(), paphSftpConfig.getPassword(), paphSftpConfig.getHost(), paphSftpConfig.getPort());
            //2 校验文件是否存在
            int i = 0;
            boolean fileExistsFlag = false;
            while (i < 30 && !fileExistsFlag) {
                if (i > 0) {
                    Thread.sleep(1000 * 60 * 3);
                }
                fileExistsFlag = SftpUtils.isDirExist(path) &&
                        SftpUtils.isFileExist(path, xfTxtFile) && SftpUtils.isFileExist(path, xfMd5File) &&
                        SftpUtils.isFileExist(path, jyTxtFile) && SftpUtils.isFileExist(path, jyMd5File);
                logger.info("平安普惠正常还款文件下载,第{}次文件校验结果：{}", i + 1, fileExistsFlag);
                i++;
            }
            if (fileExistsFlag) {
                //3 下载并校验文件
                downloadFileAndCheck(path, xfLocalPath, xfTxtFile, xfMd5File);
                downloadFileAndCheck(path, jyLocalPath, jyTxtFile, jyMd5File);
                //4 关闭连接
                SftpUtils.disSftpConnect();
                return RepeatStatus.FINISHED;
            } else {
                throw new Exception("平安普惠正常还款文件下载，文件不存在");
            }
        };
    }

    private void downloadFileAndCheck(String path, String localPath, String txtFile, String md5File) throws Exception {
        Path lPath = Paths.get(localPath);
        if (!Files.isDirectory(lPath)) {
            try {
                Files.createDirectories(lPath);
            } catch (IOException e) {
                logger.error("创建目录失败", e);
            }
        }
        SftpUtils.download(path + txtFile, localPath + txtFile);
        SftpUtils.download(path + md5File, localPath + md5File);
        try (LineNumberReader reader = new LineNumberReader(new FileReader(localPath + md5File))) {
            String str = Md5utils.getFileMD5String(new File(localPath + txtFile));
            if (!str.equals(reader.readLine())) {
                logger.info("{}校验md5不正确",txtFile);
                throw new Exception("平安普惠正常还款文件下载，文件校验不通过");
            }
        }
    }
}
